<template>
  <Modal :value="visible"
         width="571"
         footer-hide
		 :closable="false"
         @on-visible-change="onChangeVisible">
		<div class="modal-cont">
		<slot></slot>
      <div class="mapDiv"
           ref="positionDetailmapDiv">
      </div>
    </div>
  </Modal>
</template>

<script>
import tMap from '@/utils/tMap'
export default {
  components: {},
  model: {
    prop: 'visible',
    event: 'onChange'
  },
  props: {
    visible: Boolean,
    address: String,
    lng: [Number, String],
    lat: [Number, String]
  },
  data () {
    return {
      map: null,  // 天地图实例
      zoom: 14, // 初始地图缩放等级
    }
  },
  watch: {
    visible (newVal) {
      newVal && this.init()
    },
  },
  mounted () {
    // this.init()
  },
  methods: {
    init () {
      if (!this.map) return this.createMap()
      this.createMarker()
    },
    // 生成地图
    createMap () {
      tMap.init().then((T) => {
        this.map = new T.Map(this.$refs.positionDetailmapDiv)
        this.createMarker()
      }).catch(err => {
        console.log(err);
        this.$Message.info('地图加载失败,请刷新浏览器')
      })
    },
    // 生成标记点
    async createMarker () {
      //创建图片对象
      let icon = new T.Icon({
        iconUrl: require('../../../../assets/main/guidepost.png'),
        iconSize: new T.Point(24, 32),
        iconAnchor: new T.Point(10, 30)
      })
      let lnglat = new T.LngLat(this.lng, this.lat)
      let marker = new T.Marker(lnglat, { icon: icon })
      let address = this.address
      if (!address) {
        address = await this.getAddress(lnglat)
      }
      let content = `<div>${this.address}</div>`
      let label = new T.Label({ text: content, position: lnglat, offset: new T.Point(0, -40) })
      this.map.centerAndZoom(lnglat, this.zoom)
      this.map.addOverLay(marker)
      this.map.addOverLay(label)
    },
    // 逆地理编码
    async getAddress (lnglat) {
      const geocode = new T.Geocoder()
      return new Promise((resolve) => {
        geocode.getLocation(lnglat, (e) => {
          if (e.getStatus() === 0) {
            const addressComponent = e.getAddressComponent()
            resolve(addressComponent.address)
          } else {
            resolve(lnglat.lng + ',' + lnglat.lat)
          }
        })
      })
    },
    onChangeVisible (boo) {
      if (!boo) {
        this.map.clearOverLays()
        this.$emit('onChange', false)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.modal-cont{
	width: 571px;
	height: 442px;
	background-image: url(../../../../assets/new/new_video_4.png);
	background-size: 100% 100%;
}

.mapDiv {
	width: 80%;
	height: 260px;
	margin: 15px auto 0;
}
::v-deep{
	.ivu-modal {
	    top: 50%;
		margin-top: -221px;
		.ivu-modal-content {
		    box-shadow: 0 0 5px 0 rgba(37,187,150,0) !important;
		    background: rgba(26, 26, 26, 0) !important;
		}
	}
	
}
</style>
